package yxy.apple.util.mongodb;

import java.util.Arrays;

import org.bson.Document;

import com.alibaba.fastjson.parser.ParserConfig;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoConnection {
	MongoClient mongoClient;

	public void connect(String address, int port, String user, String source, String password) {
		MongoCredential credential = MongoCredential.createCredential(user, source, password.toCharArray());
		mongoClient = MongoClients.create(MongoClientSettings.builder()
				.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress(address, port)))).credential(credential).build());
	}

	public static void main(String[] args) {
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true);

		MongoConnection connection = new MongoConnection();
		connection.connect("192.168.0.202", 27017, "root", "admin", "root");

		MongoDatabase database = connection.mongoClient.getDatabase("xian_test");
//		MongoCollection<Document> collection = database.getCollection("test");
//		Document doc = new Document("name", "jhahah").append("type", 2);
//		collection.insertOne(doc);

		MongoCollection<Document> collection = database.getCollection("test");
//		Document doc = Document.parse(
//		JSONObject doc = JSONObject.parseObject(
//				"{\"@type\":\"yxy.game.pm2.bean.PlayerBean\",\"avatar\":24551,\"city\":0,\"code\":\"00okzq\",\"createTime\":\"2021-06-18T18:10:31.686+08:00\",\"guide\":\"{\\\"guildid\\\":-1,\\\"changename\\\":1,\\\"newtaskid\\\":1601}\",\"head\":24551,\"headframe\":101,\"level\":52,\"name\":\"诸 涵阳\",\"power\":1190071,\"serverId\":1,\"title\":0,\"town\":0,\"uid\":1487,\"updateTime\":\"2021-06-18T18:10:31.835+08:00\",\"upgradeTime\":\"2021-06-18T18:10:31.686+08:00\",\"viplevel\":0}");
//		collection.insertOne(doc);
//
		for (Document obj : collection.find(Document.parse("{'avatar':24551}"))) {
			System.out.println(obj);
		}

	}
}
